package 力扣._977;

class Solution {
    public int[] sortedSquares(int[] nums) {
        // 先平方，再找转折点，在向左右合并有序数组
        for (int i = 0; i < nums.length; i++) {
            nums[i] = nums[i] * nums[i];
        }
        int i = 0;
        while (i < nums.length - 1 && nums[i] >= nums[i + 1]) i++;

        if (i == 0)
            return nums;
        int[] result = new int[nums.length];
        int r_i = 0;
        int l = i - 1, r = i;

        while (l >= 0 && r < nums.length) {
            if (nums[l] < nums[r]) {
                result[r_i++] = nums[l--];
            } else
                result[r_i++] = nums[r++];
        }
        while (l >= 0) result[r_i++] = nums[l--];
        while (r < nums.length) result[r_i++] = nums[r++];
        return result;

    }
}